MODULE erosion
  
  USE definitions
  
  IMPLICIT NONE
  
CONTAINS
 
  
  !------------------------------------------------------------
  !------------------------------------------------------------
  SUBROUTINE calcE0 (pos, E)
    
    USE definitions
    
    IMPLICIT NONE
    
    INTEGER, INTENT(in), DIMENSION(2) :: pos
    REAL, INTENT(out) :: E
    
    E = E0 + (E1-E0)/REAL(ysize)*pos(2)
    
  END SUBROUTINE calcE0
  !------------------------------------------------------------
  
  !------------------------------------------------------------
  !Subroutine to call calc_pe and erode slab from cell depending on erosion probaility
  !------------------------------------------------------------
  FUNCTION erode (pos, trig)
    
    USE definitions
    USE functions
    
    IMPLICIT NONE
    
    INTEGER				:: x, y
    INTEGER, INTENT(in) :: trig
    REAL				:: r, pe
    REAL				:: erode, E
    INTEGER, INTENT(in), DIMENSION(2)	:: pos
    x = pos(1)
    y = pos(2)
    
    CALL random_number(r)

    IF(gradE == 1) THEN
       CALL calcE0(pos, E)
    ELSEIF(gradE == 0) THEN
       E = E0
    ENDIF

    erode = E*(1.0+par1*TANH(gradient_h(pos)))/2.0
    
    IF(atan(gradient_h(pos))<-15/180*pi .AND. eshadow == 1) erode = 0

    IF(Sandpit(x,y)%Slabnumber >= erode) THEN
       IF(trig == 1) Sandpit(x,y)%Slabnumber = Sandpit(x,y)%Slabnumber - erode
    ELSEIF(Sandpit(x,y)%Slabnumber < erode .AND. Sandpit(x,y)%Slabnumber > 0) THEN
       erode = Sandpit(x,y)%Slabnumber
       IF(trig == 1) Sandpit(x,y)%Slabnumber = 0
    ELSEIF(Sandpit(x,y)%Slabnumber <= 0) THEN
       erode = 0
    ENDIF

  END FUNCTION erode
  !------------------------------------------------------------
  
END MODULE erosion
  
